#version 150

in vec2 Texcoord;

out vec4 outColor;

uniform float focalLength;
uniform float focusDistance;
uniform float focalRatio;
uniform float PPM;

uniform sampler2D postprocTexture;
uniform sampler2D depthTexture;

const float blurSizeH = 1.0 / 800.0;
const float blurSizeV = 1.0 / 600.0;

void main()
{
	float depth = texture(depthTexture, Texcoord).r * 50000.0;
	float distanceFromFocus = depth < focusDistance ? float(focusDistance - depth) : float(depth - focusDistance);	
	float magnification = focalLength / (focusDistance - focalLength);
	float distanceDifference = depth < focusDistance ? float(focusDistance - distanceFromFocus) : float(focusDistance + distanceFromFocus);
	float blurDiameter = ((focalLength * magnification) / focalRatio) * (distanceFromFocus / distanceDifference);
		
	blurDiameter *= PPM;
	int blurPixels = int(blurDiameter / 2.0);
	
	if (blurPixels > 9)
	{
		blurPixels = 9;
	}
	
	int numPixels = (blurPixels * 2 + 1) * (blurPixels * 2 + 1);
	vec3 sum = vec3(0.0);	
	
	for (int x = -blurPixels; x <= blurPixels; ++x)
	{
		for (int y = -blurPixels; y <= blurPixels; ++y)
		{
			sum += (texture(postprocTexture, vec2(Texcoord.x + x * blurSizeH, Texcoord.y + y * blurSizeV)).rgb) / numPixels;
		}
	}
	
	outColor.rgb = sum;
	outColor.a = 1.0;
}